const { Captcha } = require('../models');
const { BadRequest } = require('http-errors');
const { success, failure } = require('../utils/responses');
const moment = require('moment');
module.exports = async (req, res, next) => {
  try {
    const { captchaId, captchaText } = req.body;
    const TIME_OUT = 60 * 1000; //验证码1分钟过期
    if (!captchaText) {
      throw new BadRequest('请输入验证码');
    }

    const captcha = await Captcha.findOne({ where: { id: captchaId } });
    if (!captcha) {
      throw new BadRequest('验证码已过期');
    }
    if (captchaText.toLowerCase() !== captcha.text.toLowerCase()) {
      //忽略大小写
      throw new BadRequest('验证码错误');
    }

    if (moment().diff(captcha.createdAt) > TIME_OUT) {
      await captcha.destroy();
      throw new BadRequest('验证码已过期');
    }
    await captcha.destroy();
    next();
  } catch (error) {
    failure({ res, error });
  }
};
